package com.jdew.thkj.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.model.TradeResult;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.AlibcConstants;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.CommonWebView;
import com.jdew.thkj.activity.JDPartActivity;
import com.jdew.thkj.activity.JdActivity;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.activity.MineErCodeActivity;
import com.jdew.thkj.activity.NewrEcruitsExclusiveActivity;
import com.jdew.thkj.activity.NinePointNineActivity;
import com.jdew.thkj.activity.PddActivity;
import com.jdew.thkj.activity.RankActivity;
import com.jdew.thkj.activity.TaoBaoActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.activity.TxWebViewActivity;
import com.jdew.thkj.activity.VoucherCenterActivity;
import com.jdew.thkj.activity.WebViewActivity;
import com.jdew.thkj.adapter.BituiAdapter;
import com.jdew.thkj.adapter.HomeListAdapter;
import com.jdew.thkj.adapter.WrapAdapter;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.bean.BannerBean;
import com.jdew.thkj.bean.DynamicLogoBean;
import com.jdew.thkj.bean.RankBean;
import com.jdew.thkj.bean.RunningLightsBean;
import com.jdew.thkj.bean.ZhaoshangBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.GlideImageLoader;
import com.jdew.thkj.manager.WrapContentGridLayoutManager;
import com.jdew.thkj.manager.WrapContentLinearLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.view.CornerTransform;
import com.marquee.dingrui.marqueeviewlib.MarqueeView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author yangyang
 * @date 2017/11/20
 */

public class HomeListFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.smartRefresh)
    SmartRefreshLayout smartRefreshLayout;
    private Banner banner;
    private RecyclerView bitui;
    private HomeListAdapter adapter;
    private List<RankBean.DataBean> list;
    private List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> list2;
    private List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> list3;
    private int page = 1;
    private BituiAdapter bituiAdapter;
    private WrapAdapter<HomeListAdapter> madpter;
    private List<BannerBean.DataBean> bannerList;
    private MarqueeView marqueeView;
    private ViewFlipper flipper;
    private Dialog mWeiboDialog;
    private ImageView tb, fz, jd, pdd, czzx, inviter, xsjc, tmgj, tmcs, gjg, go, nine, high, toutiao, kb;
    private DecimalFormat df = new DecimalFormat("0.00");
    private String quan;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_home_list2;
    }

    @Override
    protected void onCreateViewT() {
        mActivity = (MainActivity) getActivity();
        sp = mActivity.getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(mActivity);
        list = new ArrayList<>();
        list2 = new ArrayList<>();
        adapter = new HomeListAdapter(mActivity, list);
        bituiAdapter = new BituiAdapter(mActivity, list2);
        madpter = new WrapAdapter<>(adapter);
        addView();
        //双排显示
        recycleView.setLayoutManager(new WrapContentGridLayoutManager(mActivity, 2, GridLayoutManager.VERTICAL, false));
        bitui.setLayoutManager(new WrapContentLinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        madpter.adjustSpanSize(recycleView);
        recycleView.setAdapter(madpter);
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(mActivity));
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(mActivity));
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                RequestData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                smartRefreshLayout.setEnableLoadMore(true);
                if (null == bannerList || bannerList.size() == 0) {
                    getBanner();
                }
                if (list2.size() == 0) {
                    bitui();
                }
                if (null == list3 || list3.size() == 0) {
                    GetChoice();
                }
                if (null != marqueeView) {
                    RunningLights(marqueeView, true);
                }
            }
        });
        bitui.setAdapter(bituiAdapter);
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    String itemId = list.get(position).getTb_goods_id();
                    toDetail(itemId);
                }
            }
        });
        bituiAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    Intent in = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(in);
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    String itemId = list2.get(position).getNum_iid();
                    toDetail(itemId);
                }
            }
        });
    }

    private void addView() {
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.head_layout, null);
        marqueeView = layout.findViewById(R.id.marquee);
        RunningLights(marqueeView,true);
        banner = layout.findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        getBanner();
        bitui = layout.findViewById(R.id.bitui);
        flipper = layout.findViewById(R.id.filpper);
        tb = layout.findViewById(R.id.tb);
        fz = layout.findViewById(R.id.fz);
        jd = layout.findViewById(R.id.jd);
        czzx = layout.findViewById(R.id.czzx);
        pdd = layout.findViewById(R.id.pdd);
        inviter = layout.findViewById(R.id.inviter);
        xsjc = layout.findViewById(R.id.xsjc);
        tmgj = layout.findViewById(R.id.tmgj);
        tmcs = layout.findViewById(R.id.tmcs);
        gjg = layout.findViewById(R.id.gjg);
        go = layout.findViewById(R.id.go);
        nine = layout.findViewById(R.id.nine);
        high = layout.findViewById(R.id.high);
        toutiao = layout.findViewById(R.id.toutiao);
        kb = layout.findViewById(R.id.kb);
        tb.setOnClickListener(this);
        fz.setOnClickListener(this);
        jd.setOnClickListener(this);
        pdd.setOnClickListener(this);
        go.setOnClickListener(this);
        nine.setOnClickListener(this);
        high.setOnClickListener(this);
        czzx.setOnClickListener(this);
        inviter.setOnClickListener(this);
        xsjc.setOnClickListener(this);
        tmcs.setOnClickListener(this);
        tmgj.setOnClickListener(this);
        gjg.setOnClickListener(this);
        madpter.addHeaderView(layout);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (sp.getString("userId", "").equals("")) {
                    startActivity(LoginActivity.class);
                    return;
                }
                if (bannerList.size() > 0 && null != bannerList.get(position).getBannerTypeId()) {
                    if (bannerList.get(position).getBannerTypeId().equals("1")) {
                        return;
                    } else if (bannerList.get(position).getBannerTypeId().equals("2")) {
                        Bundle b = new Bundle();
                        b.putSerializable("itemId", bannerList.get(position).getBannerContent());
                        startActivity(TbProductDetailActivity.class, b);
                    } else if (bannerList.get(position).getBannerTypeId().equals("3")) {
                        Intent in = new Intent(mActivity, CommonWebView.class);
                        in.putExtra("url", bannerList.get(position).getBannerContent());
                        startActivity(in);
                    } else if (bannerList.get(position).getBannerTypeId().equals("4")) {
                        String url = bannerList.get(position).getBannerContent();
                        if (openAlipayPayPage(mActivity, url)) {
                        } else {
                            ToastUtils.getInstance(mActivity).showMessage("打开支付宝失败，请确认已安装支付宝");
                        }
                    } else if (bannerList.get(position).getBannerTypeId().equals("5")) {
                        String url = bannerList.get(position).getBannerContent();
                        getUrl(url);
                    } else if (bannerList.get(position).getBannerTypeId().equals("7")) {
                        Intent in = new Intent(mActivity, NewrEcruitsExclusiveActivity.class);
                        startActivity(in);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tb: {
                Intent in = new Intent(mActivity, TaoBaoActivity.class);
                startActivity(in);
            }
            break;
            case R.id.jd: {
                Intent in = new Intent(mActivity, JDPartActivity.class);
                startActivity(in);
            }
            break;
            case R.id.nine: {
                Intent in = new Intent(mActivity, NinePointNineActivity.class);
                startActivity(in);
            }
            break;
            case R.id.go: {
                Intent in = new Intent(mActivity, RankActivity.class);
                in.putExtra("type", 1);
                in.putExtra("title", "超级抢购");
                startActivity(in);
            }
            break;
            case R.id.high: {
                Intent in = new Intent(mActivity, RankActivity.class);
                in.putExtra("type", 2);
                in.putExtra("title", "24小时销量榜");
                startActivity(in);
            }
            break;
            case R.id.fz: {
                GetFlyingPig();
            }
            break;
            case R.id.tmcs: {
                GetTmSupermarket();
            }
            break;
            case R.id.tmgj: {
                GetTmInternationaln();
            }
            break;
            case R.id.gjg: {
                ToastUtils.getInstance(mActivity).showMessage("开发中,敬请期待...");
            }
            break;
            case R.id.xsjc: {
                Intent in = new Intent(mActivity, TxWebViewActivity.class);
                in.putExtra("url", "http://www.taohuikeji.com/h5Web/app_xinshoujiaocheng/Index.html");
                in.putExtra("title", "新手教程");
                startActivity(in);
            }
            break;
            case R.id.czzx: {
                startActivity(VoucherCenterActivity.class);
            }
            break;
            case R.id.pdd: {
                startActivity(PddActivity.class);
            }
            break;
            case R.id.inviter: {
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                    return;
                }
                Intent in = new Intent(mActivity, MineErCodeActivity.class);
                in.putExtra("url", sp.getString("UserImgUrl", ""));
                startActivity(in);
            }
            break;
            default:
                break;
        }
    }

    public void openTaoBao(String url) {                      //唤醒淘宝
        //提供给三方传递配置参数
        Map<String, String> exParams = new HashMap<>();
        exParams.put(AlibcConstants.ISV_CODE, "appisvcode");
        AlibcShowParams showParams = new AlibcShowParams(OpenType.Native, false);
        AlibcBasePage page = new AlibcPage(url);
        AlibcTrade.show(mActivity, page, showParams, null, exParams,
                new AlibcTradeCallback() {

                    @Override
                    public void onFailure(int i, String s) {

                    }

                    @Override
                    public void onTradeSuccess(TradeResult tradeResult) {

                    }
                });
    }

    public void bitui() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetWillpush(1, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "PageIndex1")).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ZhaoshangBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ZhaoshangBean bean) {
                list2.clear();
                if (bean.isSuccess()) {
                    list2.addAll(bean.getData().getTbk_uatm_favorites_item_get_response().getResults().getUatm_tbk_item());
                    bituiAdapter.setDataList(list2);
                }
                RequestData();
            }
        });
    }

    public void GetChoice() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        list3 = new ArrayList<>();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetChoice(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ZhaoshangBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ZhaoshangBean bean) {
                list3.clear();
                if (bean.isSuccess()) {
                    list3.addAll(bean.getData().getTbk_uatm_favorites_item_get_response().getResults().getUatm_tbk_item());
                    int size = list3.size();
                    for (int i = 0; i < size; i++) {
                        final int finalI = i;
                        View v = LayoutInflater.from(mActivity).inflate(R.layout.item_flipper, null);
                        flipper.addView(v);
                        TextView sales = v.findViewById(R.id.sales);
                        TextView name = v.findViewById(R.id.name);
                        TextView price = v.findViewById(R.id.price);
                        TextView beforeprice = v.findViewById(R.id.beforeprice);
                        ImageView product = v.findViewById(R.id.product);
                        beforeprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        String str = list3.get(i).getCoupon_info();
                        if (null != str) {
                            quan = list3.get(i) == null ? "0" : str.split("元")[1].replace("减", "");
                        } else {
                            quan = "0";
                        }
                        sales.setText("  热销" + list3.get(i).getVolume() + "  ");
                        name.setText(list3.get(i).getTitle());
                        price.setText("券后¥" + df.format(Double.parseDouble(list3.get(i).getZk_final_price()) - Double.parseDouble(quan)));
                        beforeprice.setText(list3.get(i).getZk_final_price());
                        RequestOptions options = new RequestOptions().override(150, 150).placeholder(R.mipmap.ploder).priority(Priority.HIGH);
                        Glide.with(mActivity).load(list3.get(i).getPict_url()).apply(options).into(product);
                        v.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (null != list3 && list3.size() != 0) {
                                    if (sp.getString("SpareTwo", "").equals("")) {
                                        Intent in = new Intent(mActivity, LoginActivity.class);
                                        startActivity(in);
                                    } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                                        toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                                    } else {
                                        String itemId = list3.get(finalI).getNum_iid();
                                        toDetail(itemId);
                                    }
                                }
                            }
                        });
                    }
                    bitui();
                }
            }
        });
    }

    public void RunningLights(final MarqueeView marqueeView, final Boolean istrue) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        final List<String> list = new ArrayList<String>();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).RunningLights(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<RunningLightsBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(RunningLightsBean bean) {
                list.clear();
                if (bean.getCode().equals("0")) {
                    for (int i = 0; i < bean.getData().size(); i++) {
                        list.add(bean.getData().get(i).getContenText());
                    }
                    marqueeView.setContent(list);
                    if (istrue) {
                        RequestData();
                    }
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public void RequestData() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetRealTimeSales(page, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "PageIndex" + page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                EventBus.getDefault().post("finishloading");
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                smartRefreshLayout.finishRefresh();
                smartRefreshLayout.finishLoadMore();
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                RankBean bean = JSONObject.parseObject(obj.toString(), RankBean.class);
                if (bean.isSuccess()) {
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    madpter.notifyDataSetChanged();
                    EventBus.getDefault().post("finishloading");
                }
            }
        });
    }

    public void getUrl(String url) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        //会场接口
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody requestBodyPost = new FormBody.Builder()
                .add("guid", sp.getString("userId", ""))
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBodyPost)
                .addHeader("staffid", RegexValidateUtils.getUniquePsuedoID())
                .addHeader("timestamp", timesamp)
                .addHeader("nonce", numsamp)
                .addHeader("signature", MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase())
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                JSONObject json = JSONObject.parseObject(result);
                if (null == json.get("code")) {
                    Looper.loop();
                }
                if (json.getString("code").equals("-1")) {
                    Looper.loop();
                }
                String url = json.getString("data");
                openTaoBao(url);
                Looper.loop();
            }
        });
    }

    @Override
    public void initData() {

    }

    public void getBanner() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        if (!DeviceUtils.isNetworkAvalible(mActivity)) {
            if (!mActivity.isFinishing()) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                ToastUtils.getInstance(mActivity).showMessage("网络连接错误,请检查!");
            }
            return;
        }
        final List<String> listmap = new ArrayList<>();
        if (null == bannerList) {
            bannerList = new ArrayList<>();
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetBannerList(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<BannerBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(BannerBean bean) {
                if (bean.getCode().equals("0")) {
                    if (listmap.size() != 0) {
                        listmap.clear();
                    }
                    bannerList.addAll(bean.getData());
                    for (int i = 0; i < bean.getData().size(); i++) {
                        listmap.add(bannerList.get(i).getBannerUrl());
                    }
                    banner.setImages(listmap);
                    banner.start();
                    getLogoList();
                }
            }
        });
    }

    public void getLogoList() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        final List<String> logoList = new ArrayList<>();
        if (null == bannerList) {
            bannerList = new ArrayList<>();
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetLogoList(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<DynamicLogoBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(DynamicLogoBean bean) {
                if (bean.getCode().equals("0")) {
                    logoList.add(bean.getData().getLogoTianmao());
                    logoList.add(bean.getData().getLogoTmGuoji());
                    logoList.add(bean.getData().getLogoChaoshi());
                    logoList.add(bean.getData().getLogoJingDong());
                    logoList.add(bean.getData().getLogoPdd());
                    logoList.add(bean.getData().getLogoFz());
                    logoList.add(bean.getData().getLogoTmChongzhi());
                    logoList.add(bean.getData().getLogoGuojiGuan());
                    logoList.add(bean.getData().getLogoYaoqing());
                    logoList.add(bean.getData().getLogoJiaocheng());
                    logoList.add(bean.getData().getLogoKuaibao());
                    logoList.add(bean.getData().getLogoToutiao());
                    logoList.add(bean.getData().getLogoJiujiu());
                    logoList.add(bean.getData().getLogoQianggou());
                    logoList.add(bean.getData().getLogoRexiao());
                    RequestOptions options = new RequestOptions().priority(Priority.HIGH);
                    RequestOptions options1 = new RequestOptions().placeholder(R.mipmap.nine).priority(Priority.HIGH);
                    RequestOptions options2 = new RequestOptions().placeholder(R.mipmap.go).priority(Priority.HIGH);
                    RequestOptions options3 = new RequestOptions().placeholder(R.mipmap.high).priority(Priority.HIGH);
                    Glide.with(mActivity).load(logoList.get(0)).apply(options).into(tb);
                    Glide.with(mActivity).load(logoList.get(1)).apply(options).into(tmgj);
                    Glide.with(mActivity).load(logoList.get(2)).apply(options).into(tmcs);
                    Glide.with(mActivity).load(logoList.get(3)).apply(options).into(jd);
                    Glide.with(mActivity).load(logoList.get(4)).apply(options).into(pdd);
                    Glide.with(mActivity).load(logoList.get(5)).apply(options).into(fz);
                    Glide.with(mActivity).load(logoList.get(6)).apply(options).into(czzx);
                    Glide.with(mActivity).load(logoList.get(7)).apply(options).into(gjg);
                    Glide.with(mActivity).load(logoList.get(8)).apply(options).into(inviter);
                    Glide.with(mActivity).load(logoList.get(9)).apply(options).into(xsjc);
                    Glide.with(mActivity).load(logoList.get(12)).apply(options1).into(nine);
                    Glide.with(mActivity).load(logoList.get(13)).apply(options2).into(go);
                    Glide.with(mActivity).load(logoList.get(14)).apply(options3).into(high);
                    Glide.with(mActivity).load(logoList.get(10)).apply(options).into(kb);
                    Glide.with(mActivity).load(logoList.get(11)).apply(options).into(toutiao);
                    GetChoice();
                }
            }
        });
    }

    public void toDetail(String itemId) {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemId);
        startActivity(TbProductDetailActivity.class, b);
    }

    public void GetFlyingPig() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap<>();
        map.put("guid", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetFlyingPig(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "guid" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    String fzurl = json.getString("data");
                    openTaoBao(fzurl);
                } else {
                    ToastUtils.getInstance(mActivity).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void GetTmSupermarket() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap<>();
        map.put("guid", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).Getchaoshi(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "guid" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    String fzurl = json.getString("data");
                    openTaoBao(fzurl);
                } else {
                    ToastUtils.getInstance(mActivity).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void GetTmInternationaln() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap<>();
        map.put("guid", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).Getimport(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "guid" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    String fzurl = json.getString("data");
                    openTaoBao(fzurl);
                } else {
                    ToastUtils.getInstance(mActivity).showMessage(json.getString("message"));
                }
            }
        });
    }

    public boolean openAlipayPayPage(Context context, String content) {
        try {
            String alipayqr = "alipayqr://platformapi/startapp?clientVersion=3.7.0.0718";
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("text", content));
            openUri(context, alipayqr);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送一个intent
     */
    private void openUri(Context context, String s) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(s));
        context.startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != list) {
            list.clear();
            list = null;
        }
        if (null != list2) {
            list2.clear();
            list2 = null;
        }
        if (null != list3) {
            list3.clear();
            list3 = null;
        }
        if (null != bannerList) {
            bannerList.clear();
            bannerList = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (null != flipper) {
            flipper.stopFlipping();
        }
        if (null != marqueeView) {
            marqueeView.stopRoll();
        }

    }

    //如果你需要考虑更好的体验，可以这么操作

    @Override
    public void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != marqueeView) {
            RunningLights(marqueeView,false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String source) {
        if (source.equals("refreshnonetwork")) {
            getBanner();
            if (null != marqueeView) {
                RunningLights(marqueeView,true);
            }
        }
    }
}